<?php
#################################
# Metadata Enhancement for Repositories (MER) 
# This software is an overlay repository search interface that uses a 
# text mined index of terms.
# Copyright (C) 2011  Rory McNicholl (University of London Computer Centre), Robert Drinkall (University College London)

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Contact repositories@ulcc.ac.uk
# http://www.ulcc.ac.uk

##################################

include("../mer.php");

$mer = new MER();

$mess = false;

###### merlin presentation parameters #######
$search_term = $_REQUEST['search_str'];

$t_number = 40;//TODO: user definable param (not implemented in merlin.js yet...)
if(isset($_REQUEST["cloud_size"]) && is_numeric($_REQUEST["cloud_size"])){
	$t_number = $_REQUEST["cloud_size"];
}
$t_format = "cloud";
if(isset($_REQUEST["as_cloud"]) && $_REQUEST["as_cloud"] == "on")
	$t_format = "cloud";
else
	$t_format = "list";

$one_doc = false;
$term_id = false;
if(isset($_REQUEST["ids_str"])){
	$ids_arr = split("\|",$_REQUEST["ids_str"]);
}elseif(isset($_REQUEST["recordid"]) && is_numeric($_REQUEST["recordid"])){
	$one_doc = true;
}elseif(isset($_REQUEST["termid"]) && is_numeric($_REQUEST["termid"])){
	$term_id = $_REQUEST["termid"];

}else{
	$mess="<response>params not found</response>";
}

$output_format = "html";
if(isset($_REQUEST["output_format"]))
	$output_format = $_REQUEST["output_format"];

######## term collection ###########
$terms = array(); #terms end up here
$t_w_min = 100; #start with hi min
$t_w_max = 0; #and lo max
$t_w_num_terms = 0; #count number of terms ?

if($one_doc){
	$sql = sprintf("select term, termine_score, in_metadata, ma.term_id, record_id from %s_associations ma, %s_terms mt where ma.record_id = '%s' and ma.term_id = mt.term_id order by -termine_score limit %d",
		$mer->config->table_prefix,
		$mer->config->table_prefix,
		$mer->mres($_REQUEST["recordid"]),
		$t_number);

	$result = @mysql_query($sql, $mer->db) or die("could not complete your query $sql");
	while($row = @mysql_fetch_array($result)) {
		if($row["termine_score"] > $t_w_max)
			$t_w_max = $row["termine_score"];
		if($row["termine_score"] < $t_w_min)
			$t_w_min = $row["termine_score"];
		$terms[$row["term"]]=$row;
		$t_w_num_terms++;
	}
	$num_term_docs = 1;
}elseif($term_id){

	$sql = sprintf("select record_id, term, termine_score, in_metadata, term_id from %s_associations ma join %s_terms mt using (term_id) where term_id = %d ",
			$mer->config->table_prefix,
			$mer->config->table_prefix,
			$term_id);
	error_log($sql);
	$result = @mysql_query($sql, $mer->db) or die("could not complete your query $sql");
	while($row = @mysql_fetch_array($result)) {
		$r_id = array_pop(split(":",$row['record_id']));
		$row["citation"] = $mer->do_cURL("{$mer->config->repo_url}/cgi/export/{$r_id}/HTML/{$mer->config->repo_id}-{$r_id}.html");
		$terms[$row["record_id"]]=$row;

		$t_w_num_terms++;
	}
//	$num_term_docs = 1;
}else{
	$ids_sql_str = "'".join("','",$ids_arr)."'";
	$sql = sprintf("select count(*) from %s_records where record_id in (%s)",$mer->config->table_prefix,$ids_sql_str);
	$result = @mysql_query($sql, $mer->db) or die("could not complete your query $sql");
	$row = mysql_fetch_row($result);
	$num_term_docs = $row[0];
        $per_doc = ceil($t_number/$num_term_docs);

	foreach($ids_arr as $id){
		$sql = sprintf("select term, termine_score, in_metadata, ma.term_id, record_id from %s_associations ma, %s_terms mt where ma.record_id = '%s' and ma.term_id = mt.term_id order by -termine_score limit %d",
			$mer->config->table_prefix,
			$mer->config->table_prefix,
			$id,
			$per_doc);

		$result = @mysql_query($sql, $mer->db) or die("could not complete your query $sql");
                while($row = @mysql_fetch_array($result)) {
                        if($row["termine_score"] > $t_w_max)
                                $t_w_max = $row["termine_score"];
                        if($row["termine_score"] < $t_w_min)
                                $t_w_min = $row["termine_score"];
#                       $terms[$row["term"]][]=$row; #might not overwrite shared terms, but other issues...
                        $terms[$row["term"]]=$row; #will overwrite shared terms
                        $t_w_num_terms++;
		}
	}
	if($t_w_num_terms > $t_number){
                #sort by scores and lop off the lower scoring terms
                uasort($terms, "score_cmp");
                if(isset($_REQUEST["as_cloud"]) && $_REQUEST["as_cloud"] == "on")
                        $terms = array_slice($terms, 0, $t_number);
        }

}

### Calculate cloud size steps if in cloud format ###
if($t_format == "cloud"){
	$t_w_num_sizes = 10;
	//Cloud font size range (em)
	$t_w_max_size = 1.8; $t_w_min_size = 0.8;

	if($t_w_max > 0){
		$t_w_step = ($t_w_num_sizes/$t_w_max)*(($t_w_max_size-$t_w_min_size)/$t_w_num_sizes);
	}else{
		$t_w_max = 0;
		$t_w_min = 0;
	}

	$default_value = 0.25; //TODO: user definable param (not implemented in merlin.js)
	if(isset($_REQUEST["start_slider_pos"]) && is_numeric($_REQUEST["start_slider_pos"])){
		$default_value = $_REQUEST["start_slider_pos"];
	}

}
$t_w_default =($t_w_max+$t_w_min)*$default_value;
$t_w_slider_default = ($t_w_max+$t_w_min)*(1-$default_value);

##### Begin the render ######
$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n";
$xml .= "<merlin xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n";
$xml.= "<tagquery>$sql</tagquery>";
$xml .= "<terms>";

if($t_format == "cloud")
	$html = '<div class="center_div cloud">';
else
	$html = '<div class="center_div list">';

$html .= <<<EOD
                <div class="merlin_thes_term" id="merlin_search_term">$search_term</div>
                <div class="merlin_thes_term thes_down"></div>
                <div class="merlin_thes_term thes_up"></div>
                <div class="merlin_thes_term thes_right"></div>
                <div class="merlin_thes_term thes_left"></div>
EOD;
if($t_format == "cloud")
	$html.='<ul id="cloud" class="cloud">';
else
	$html.='<ul id="list" class="list">';



// This line of html comment is parsed by jQuery into a data structure and can include any useful metadata about the query results...
$html .="<script>var t_data = { t_default: $t_w_default, t_slider_default: $t_w_slider_default, t_max: ".(integer)$t_w_max.", t_min: ".(integer)$t_w_min.", t_num_terms: $t_w_num_terms, t_num_term_docs: $num_term_docs } </script>";

$sorted = array_keys($terms);

if($t_format == "cloud"){
        #sort alphabetically for cloud
        natcasesort($sorted);
}

$html .= '<div id="actual_list">';

$i=0;
foreach($sorted as $key){
#	error_log($key);
	$row = $terms[$key];
#	$assocs = $terms[$key];
#	foreach($assocs as $row){
		$term = $row['term'];
		$term_id = $row['term_id'];
		$score = $row['termine_score'];
		$in_meta = $row['in_metadata'];
		$title = $row['title'];
		$record_id = $row['record_id'];
		if(isset($row["creators"])) $creators = $row["creators"];
		if(isset($row["citation"])) $citation = $row["citation"];

		$t_weight = $score;
		$t_weight_size = $t_w_min_size+($t_weight*$t_w_step);
#		error_log($term." : ".$score);

		$term_element = <<<EOT
		<term>
			<termid>$term_id</termid>
			<text>$term</text>
			<score>$score</score>
			<in_meta>$in_meta</in_meta>
			<record_id>$record_id</record_id>
			<citation>$citation</citation>
		</term>
EOT;

		$xml .= $term_element;

		if($t_weight < $t_w_default)
			$html .= "<li style='font-size: ".$t_weight_size."em;' t_weight='".$t_weight."' class='hidden'><a href='' id='term_tag_".$term_id."'>".$term."</a></li>";
		else
			$html .= "<li style='font-size: ".$t_weight_size."em' t_weight='".$t_weight."'><a href='' id='term_tag_".$term_id."'>".$term."</a></li>";
		$i++;
#	}
}
$xml .= "</terms></merlin>";
$html .="</div></ul></div>";
if($output_format == "html")
	print $html; #using ready made html for speed...
else{
header('Content-Type: text/xml');

	print $xml;
}

#### leaving function in this script for now #####
function score_cmp($a, $b)
{
    if ($a["termine_score"] == $b["termine_score"]) {
        return 0;
    }
    return ($a["termine_score"] < $b["termine_score"]) ? 1 : -1;
}

?>
